//
//  JSSComposeViewController.swift
//  WeiBoItem
//
//  Created by jss on 16/4/25.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit
import SVProgressHUD

class JSSComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

          setupUI()
        
        pictureView.controlRingtItem = {
            
            // print(self.pictureView.images.count)
            self.navigationItem.rightBarButtonItem?.enabled = true
        }
        
        pictureView.controlRingt = {
           
            self.navigationItem.rightBarButtonItem?.enabled = false
        }
        
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textview.becomeFirstResponder()
    }
  //设置界面
    private func setupUI() {
        
        self.view.backgroundColor = UIColor(white: 237/255.0, alpha: 1)
        
        //设置导航栏返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "diiClickBackBtn:")
        
        navigationItem.titleView = titleLable
        

        //设置导航栏右边发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        
        
        //默认禁止用户交互
        
       // navigationItem.rightBarButtonItem?.enabled = self.pictureView.images.count > 0
        navigationItem.rightBarButtonItem?.enabled = false
        
        print(self.pictureView.images.count)
        
        //把textView添加到view上
        view.addSubview(textview)
        
        //添加toolbarView
        view.addSubview(toolbarView)
        
        //添加pictureView
        textview.addSubview(pictureView)
        
        
        //约束textView
        textview.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.bottom.leading.equalTo(self.view)
        }
        
        //约束toolbarView
        toolbarView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(44)
            make.bottom.equalTo(self.view)
        }
        
        //约束pictureView
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(textview).offset(-20)
            make.height.equalTo(pictureView.snp_width)
        }
        
        
        
        //使用通知 监听键盘弹出时frame将要变化的时候  调用相应的方法
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameWillChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        
        //使用通知 当表情按钮点击的时候 将相应的按钮图片显示到textView上(接收通知 已经在cell里面发出通知)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonBtnDidClick:", name: JSSEmoticonBtnClickNotification, object: nil)
        
        //使用通知 当删除按钮点击的时候 将相应的按钮图片从textView上删除(接收通知 已经在cell里面发出通知)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeletebtnDidClick", name: JSSEmoticonDeleteBtnClickNotification, object: nil)
        
        
    }
    
    //实现通知监听删除按钮的点击 图片相应显示
    @objc private func emoticonDeletebtnDidClick(){
    
        //print("删除按钮收到通知")
        
        //textView回删一个
        self.textview.deleteBackward()
        
        
    
    }
    
    //实现通知监听表情按钮的点击 图片相应显示
    @objc private func emoticonBtnDidClick(info:NSNotification){
        //先取到通知发过来的emoticon表情
        let emoticon = info.userInfo!["emoticon"] as! JSSEmoticonModel
        
        //判断是否是Emoji表情
        if emoticon.type == "1" {
           
            //代表是Emoji表情
            textview.insertText((emoticon.code! as NSString).emoji())
        
        
        }else{
          
            print("图片表情点击")
            
            textview.insertEmotiocon(emoticon)
            
            //下面方法已经都抽到分类里面
//            //1.将现有文字生成一个NSMutableAttributeString
//           let originalAttr = NSMutableAttributedString(attributedString: textview.attributedText)
//            //通过表情模型生成表情图片
//            let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
//            //通过图片生成NSTextAttachment
//            let attachment = NSTextAttachment()
//            attachment.image = image
//            
//            //设置图片大小
//            let attachmentHW = textview.font!.lineHeight
//            
//            attachment.bounds = CGRect(x: 0, y: -4, width: attachmentHW, height: attachmentHW)
//            
//            //通过attachment生成一个NSAttributeString
//            let attr = NSAttributedString(attachment: attachment)
//            
//            //将第二步生成的NSAttributeString 添加到第一步生成的NSMutableAttributeString里
//            originalAttr.appendAttributedString(attr)
//            
//            
//            
//            //获取光标所在的位置
//            var selectedRange = textview.selectedRange
//            
//            //设置字体大小
//            originalAttr.addAttribute(NSFontAttributeName, value: textview.font!, range:NSMakeRange(0, originalAttr.length))
//            
//            
//            //将第三步的执行结果赋值给 textview的attributeText
//            textview.attributedText = originalAttr
//            
//            //设置光标的位置
//            selectedRange.location += 1
//            selectedRange.length = 0
//            textview.selectedRange = selectedRange
            
        
        }
    }

    //实现通知监听键盘frame变化的时候 实现的方法
    @objc private func keyboardFrameWillChanged(notifi:NSNotification){
      /*
        userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 216}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 775}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 775}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 216}}";
        UIKeyboardIsLocalUserInfoKey = 1;

        */
     
        //print(notifi)//打印出来就是上面的内容  可以取到键盘结束位置
        //拿到键盘的结束frame 拿到的frame是结构体NSRect  这里要转成CGRect
        let endFrame = ((notifi.userInfo![UIKeyboardFrameEndUserInfoKey]) as! NSValue).CGRectValue()
        
        print(endFrame)
        
        //更新toolbarView的位置(注意: 底部和右边 负数才是向上的)
        toolbarView.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.0001) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //点击导航栏返回按钮的方法实现
    @objc private func diiClickBackBtn(btn:UIBarButtonItem){
        //取消第一相应者
        self.textview.resignFirstResponder()
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //实现发送按钮的方法(点击按钮发微博)
    @objc private func send() {
        
        if pictureView.hidden {
            
            //表示没有图片 那就发送 文字微博
            
            self.sendWords()
        }else {
            
            //表示有图片发送图片和文字微博
            sendPicture()
        }
        
        
        
    }
    
    //表示有图片发送图片和文字微博
    private func sendPicture() {
        
        //发送图片微博
        //请求地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //请求参数
        let parametes = [
            
            "access_token":JSSUserAccountModel.sharedAccontModel.account?.access_token ?? "",
            "status":textview.emoticonText!
            
        ]
        let data = UIImagePNGRepresentation(self.pictureView.images.first!)!
        
        
        //抽取代码放在工具类里面  把上传拼接的步骤在工具类里面就写好了 这里就不要拼接二进制文件了
        HMNetworkTools.sharedTools.upload(url, pamaters: parametes, datas: ["pic":data]) { (responseObject, error) -> () in
            
            
            if error != nil {
                
                print("发送失败")
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
//        //发送请求 (发送请求后面的参数拼接已经放在工具类里面了 所以这里注释掉了)
//        HMNetworkTools.sharedTools.POST(url, parameters: parametes, constructingBodyWithBlock: { (formData) -> Void in
//        print(formData)//拼接的数据结构
//        
//        // 在此拼接二进制文件
//        /**
//        - 1. 要上传的二进制数据
//        - 2. 该二进制数组对应的接口里面的名字
//        - 3. 传到后台之后的文字名字。一般都乱写，因为后台基本不会使用你写的名字
//        - 4. mimeType: 告诉后台我们传上去的二进行数据具体是什么类型的
//        - image/jpeg
//        - 大类型/小类型
//        - 如果不想让后台知道：application/octet-stream
//        */
//        let data = UIImagePNGRepresentation(self.pictureView.images.first!)!
//        
//        formData.appendPartWithFileData(data, name: "pic", fileName: "uuu", mimeType: "application/octet-stream")
//        
//        
//        }, progress: nil, success: { (_, response) -> Void in
//        
//        SVProgressHUD.showSuccessWithStatus("发送成功")
//        }) { (_, error) -> Void in
//            
//            SVProgressHUD.showErrorWithStatus("发送失败")
//        }
        
    
    
    private func sendWords(){
        
        
        //发送微博文字
        //请求地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //请求参数
        let parametes = [
            "access_token":JSSUserAccountModel.sharedAccontModel.account?.access_token ?? "",
            "status":textview.emoticonText!
        ]
        //发送请求
        HMNetworkTools.sharedTools.request(HMRequestMethod.Post, urlString: url, parameters: parametes) { (responseObject, error) -> () in
            
            if error != nil {
                
                print("发送失败")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    
    
    //懒加载自定义表情键盘(emoticonView)
    private lazy var emoticonView: JSSEmotionKeyboard = {
      let keyboard = JSSEmotionKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 228)
        
        return keyboard
    
    }()
    
    //懒加载toolbarView
    private lazy var toolbarView:JSSStackToolBarView = {
        
        let toolbarview = JSSStackToolBarView(frame: CGRectZero)
        
        toolbarview.didClickBtnClosure = {[weak self] (type) in
            print(type)
            
            switch type {
                
            case .Picture:
                //选择图片
                self?.selectPicture()
                
                break
            case .Mention:
                break
            case .trend:
                break
            case .emoticon:
                self?.selectedKeyboard()
                break
            case .add:
                break
                
                
            }
        }
        
        return toolbarview
    }()
    
    
    //切换键盘的方法
    private func selectedKeyboard(){
    
//        if textview.inputView == nil {
//            
//            //代表是系统键盘  将要切换到表情键盘
//            textview.inputView = emoticonView
//        }else {
//            
//            //切换到系统键盘
//            textview.inputView = nil
//        }
        
        textview.inputView = textview.inputView == nil ? emoticonView : nil
        
        //控制器告诉toolbar当前显示的是什么键盘
        toolbarView.isSystemKeyboard = textview.inputView == nil
        
        //重新加载输入的视图
        textview.reloadInputViews()
    
    }
    
    
    
    //选择图片的方法
    private func selectPicture() {
        
        //取到图片管理控制器
        let vc = UIImagePickerController()
        
        //设置代理
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
        
    }
    
    
    
    //懒加载中间的自定义的图片view(collectionView)
    private  lazy var pictureView: JSSComposePictureView = {
    
    let picView = JSSComposePictureView(frame: CGRectZero,collectionViewLayout:UICollectionViewFlowLayout())
        
        //执行点击最后一个cell即加号按钮实现的闭包
        picView.selectedPictureClosure = {
            
            //弹出图片选择器 并且选择图片
            self.selectPicture()
            
        }
     return picView
    
    }()
    

    
    
    //懒加载标题lable
    private lazy var titleLable:UILabel = {
        
        let lable = UILabel(textColor: UIColor.blackColor(), textFont: 14)
        
        lable.numberOfLines = 0
        
        lable.textAlignment = .Center
        
        //设置文字并换行
        // lable.text = "发微博\n伟大的思想能变成巨大的财富"
        
        let text = "发微博\n伟大的思想能变成巨大的财富"
        //求出上面text中换行的文字范围
        let rang = (text as NSString).rangeOfString("伟大的思想能变成巨大的财富")
        let attrText = NSMutableAttributedString(string: text)
        
        attrText.addAttributes([NSForegroundColorAttributeName:UIColor.purpleColor(),NSStrokeColorAttributeName:UIColor.redColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: rang)
        
        //设置label文本
        lable.attributedText = attrText
        
        
        
        lable.sizeToFit()
        
        return lable
        
    }()
    
    
    //懒加载btn
    private lazy var sendBtn:UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setTitle("发送", forState: UIControlState.Normal)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        //设置不同状态下的文字颜色
        // button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置不同状态下背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        //不起作用 因为它是加载navigationItem上的
        //button.enabled = false
        
        button.frame.size = CGSize(width: 50, height: 30)
        return button
        
    }()
    
    //懒加载中间的textView
    private lazy var textview:JSSTextView = {
        
        let textfile = JSSTextView()
        
        textfile.placeHolderLable = "不要点我 不然我就消失掉...哈哈~~~啦啦啦"
        
        textfile.font = UIFont.systemFontOfSize(15)
        
        //设置代理
        textfile.delegate = self
        
        return textfile
        
    }()

}

//textView的代理方法
extension JSSComposeViewController:UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
    
        
     
//        navigationItem.rightBarButtonItem?.enabled = textview.hasText()
         navigationItem.rightBarButtonItem?.enabled = (textview.hasText() || self.pictureView.images.count > 0) ? true : false
        
      //print(self.pictureView.images.count)
    }
}

//UIImagePickerControllerDelegate分类
extension JSSComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let img = image.scaleToWidth(600)
        //先把选择的图片转换成二进制 猜测看是否选图成功
        let data = UIImagePNGRepresentation(img)
        
        //给pictrueView添加图片
        pictureView.addImages(img)
        
        //测试 选择图片保存桌面成功
        data?.writeToFile("/Users/jss/Desktop/2.png", atomically: true)
       // print("保存成功")
        
        //选择图片以后 dissmiss当前控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }




}
